<template>
	<view class="tabContent" :style="{marginTop:$u.addUnit(44 + $u.sys().statusBarHeight,'px'),}">
		<u-navbar style="z-index: 99;" :fixed="true" :safeAreaInsetTop="true">
			<view class="u-nav-slot" slot="left">
				<view class="comboSelect">
					<uni-data-select v-model="selectedCombo" :localdata="comboList" :clear="false" iconColor="#fff"
						@change="changeCombo"></uni-data-select>
				</view>
			</view>
			<view class="u-nav-slot" slot="right">
				<view class="boardSelect" @click="openBaseScreen('看板')">
					<text class="text">{{selectedBoard.boardTitle}}</text>
					<uni-icons fontFamily="CustomFontPlatform" :size="14" color="#fff">{{'\ue605'}}</uni-icons>
				</view>
			</view>
		</u-navbar>

		<view class="subcontent">
			<!-- 看板内容 -->
			<component :is="selectedBoard.boardName" ref="myComponent"></component>
		</view>
	</view>
</template>

<script>
	// ERP 看板
	import Sale from '../../commonPage/kanban/erp/sale.vue'
	import Purchase from '../../commonPage/kanban/erp/purchase.vue'
	import Warehouse from '../../commonPage/kanban/erp/warehouse.vue'
	import Finance from '../../commonPage/kanban/erp/finance.vue'
	// 小工单 看板
	import Ticket1 from '../../commonPage/kanban/ticket-1.vue'
	// qms 看板
	import Qms1 from '../../commonPage/kanban/qms-1.vue'

	export default {
		components: {
			Sale,
			Purchase,
			Warehouse,
			Finance,
			Ticket1,
			Qms1,
		},

		data() {
			return {
				modules: [], // 当前用户已开通模块				
				selectedCombo: -1, // 当前所选版本
				comboList: [], // 版本列表
				boardList: [], // 看板数据源
				selectedBoard: {
					boardID: 0,
					boardName: '',
					boardTitle: ''
				} // 当前选中看板
			}
		},

		mounted() {
			var that = this;
			uni.$on('Home_Choice', function(ret) {
				const dataCopy = JSON.parse(JSON.stringify(ret.data));
				switch (ret.type) {
					case '看板':
						that.selectedBoard.boardID = dataCopy.boardID;
						that.selectedBoard.boardName = dataCopy.boardName;
						that.selectedBoard.boardTitle = dataCopy.boardTitle;
						that.changeKanBan(that.selectedBoard);
						break;
					default:
						break;
				}
			});
		},

		created: function() {
			let that = this;
			that.getModule();
		},

		methods: {

			// 获取产品版本下属模块(APP)
			getModule() {
				let that = this;
				// console.log(this.$store.state.UserInfo.Business);
				that.Request.request('SelectActivatedModule', {
						AccountID: this.$store.state.UserInfo.Business
					}, function(res) {
						that.comboList = res.data.ds.map(item => ({
							...item,
							value: item.ModuleID,
							text: item.ModuleName
						}));
						// console.log(that.comboList);
						that.selectedCombo = that.comboList[0].value;
						// 获取当前版本下所有APP菜单
						that.getAllMenuData(that.selectedCombo, 1);
						// 获取当前版本看板列表
						that.getKanBanList();
					}, function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 获取所有菜单数据
			getAllMenuData(moduleID, option) {
				let that = this;

				that.Request.request('platform_getAppModule', {
						UserID: this.$store.state.UserInfo.UserID,
						ModuleID: moduleID,
						AccountID: this.$store.state.UserInfo.Business
					}, function(res) {
						// console.log(res);
						if (res.data.ds.length) {
							let modules = res.data.ds;
							// 初始化快捷选中状态
							res.data.ds1.forEach(item => {
								if (item.IsShortcut) {
									item.IsChecked = true;
								} else {
									item.IsChecked = false;
								}
							})
							let pages = res.data.ds1;

							modules.forEach(module => {
								// 当前模块已授权全部页面
								let modulePages = pages.filter(page => page.APPType == module.ModuleID);
								// 当前模块已授权非tabbar页面
								let moduleTreePage = modulePages.filter(page => !page.IsTabbar);
								let moduleTree = [...new Set(moduleTreePage.map(page => {
									let obj = {
										treeType: page.TreeType,
										treeTypeName: page.TreeTypeName,
										pages: []
									}
									return JSON.stringify(obj)
								}))].map(item => JSON.parse(item));
								moduleTree.forEach(tree => {
									tree.pages = moduleTreePage.filter(page => page.TreeType == tree
										.treeType);
								})
								// 当前模块已授权默认捷径(默认不允许修改)
								let moduleShortcuts = modulePages.filter(page => page.IsShortcut);
								module.shortcuts = moduleShortcuts;
								module.treeTypes = moduleTree;
								module.authPages = modulePages;
							})
							that.modules = modules;

							if (option == 1) {
								// 初始化选中APP模块
								setTimeout(() => {
									that.initAPPModule();
								}, 2000);

							}
						} else {
							that.modules = [];
						}

						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'APPModules',
							data: that.modules,
						});

						uni.$emit('refreshCenter', {});
						// console.log(that.modules);

					}, function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 获取用户APP看板(平台首页)
			getKanBanList() {
				let that = this;
				that.Request.request('PlatForm_SelectKaanBan', {
						UserID: this.$store.state.UserInfo.UserID,
						KanBanType: 2 // 移动看板
					}, function(res) {
						let data = res.data.ds;
						that.boardList = data.map(item => ({
							boardID: item.KanBanID,
							boardName: item.Path.substring(item.Path.lastIndexOf('/') + 1),
							boardTitle: item.KanBanName
						}))
						that.initKanBan();
					}, function(err) {
						console.log(err);
					}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 初始化看板
			initKanBan() {
				let that = this;
				let activeBoard = null;
				// 获取选中看板缓存
				let str = uni.getStorageSync('ActiveBoard');
				if (str) {
					activeBoard = JSON.parse(str);
					if (that.boardList.length) {
						// 缓存看板在看板列表中则选中
						let flag = that.boardList.some(board => board.boardID == activeBoard.boardID);
						if (flag) {
							that.selectedBoard.boardID = activeBoard.boardID;
							that.selectedBoard.boardName = activeBoard.boardName;
							that.selectedBoard.boardTitle = activeBoard.boardTitle;
						} else {
							that.selectedBoard.boardID = that.boardList[0].boardID;
							that.selectedBoard.boardName = that.boardList[0].boardName;
							that.selectedBoard.boardTitle = that.boardList[0].boardTitle;
						}
					}
				} else {
					if (that.boardList.length) {
						that.selectedBoard.boardID = that.boardList[0].boardID;
						that.selectedBoard.boardName = that.boardList[0].boardName;
						that.selectedBoard.boardTitle = that.boardList[0].boardTitle;
					}
				}
				that.$store.commit('ChangeAndSetStateData', {
					Name1: 'ActiveBoard',
					data: that.selectedBoard,
					StorageName: 'ActiveBoard',
					StorageData: JSON.stringify(that.selectedBoard)
				});
			},

			// 切换看板
			changeKanBan(board) {
				// console.log(board);
				let that = this;
				that.$store.commit('ChangeAndSetStateData', {
					Name1: 'ActiveBoard',
					data: board,
					StorageName: 'ActiveBoard',
					StorageData: JSON.stringify(board)
				});
			},

			organizeByTreeTypeName(arr, ds1Map) {
				// 创建一个映射来按TreeType分组数据  
				const groupedData = {};

				arr.forEach((item) => {
					const treeType = item.TreeType;
					const treeTypeName = item.TreeTypeName; // 用于分组的键  

					if (!(treeTypeName in groupedData)) {
						groupedData[treeTypeName] = {
							TreeType: treeType, // 保留TreeType  
							APPType: item.appType, // 保留APPType
							Node: [],
						};
					}

					// 检查ds1Map中是否有匹配的APPFunID  
					if (ds1Map.has(item.APPFunID)) {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: ds1Map.get(item.APPFunID), // 如果需要，直接添加IconApprove  
						});
					} else {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: []
						});
					}
				});

				// 提取分组后的数据为数组，并可能按某种逻辑排序（这里不排序，因为TreeTypeName已经是分组键）  
				const sortedData = Object.entries(groupedData).map(([treeTypeName, group]) => ({
					TreeTypeName: treeTypeName,
					...group, // 展开分组对象，它包含TreeType, APPType, APPFunID, 和 Node 数组  
				}));

				return sortedData;
			},
			// 初始化模块页面
			initModule(module) {
				let that = this;

				this.$utils.showLoading('正在加载模块');

				this.Request.request('getAPPModulePages', {
					UserID: this.$store.state.UserInfo.UserID,
					APPType: module.ModuleID,
				}, (ret) => {
					// console.log(ret)
					if (ret.status == 200) {
						const data = ret.data.ds;
						const ds1 = ret.data.ds1;

						// 预先处理ds1，以APPFunID为键，值为对应的数组  
						const ds1Map = new Map(ds1.map(row => [row.APPFunID, [row]]).reduce((acc, [key, val]) => {
							acc.set(key, [...acc.get(key) || [], ...val]);
							return acc;
						}, new Map()));

						let organizedData = that.organizeByTreeTypeName(data, ds1Map);
						organizedData = organizedData.sort((a, b) => a.TreeType - b.TreeType);

						// 这里获取了模块以及页面的权限树，将 IsTabbar 为true的筛选出来，作为底部栏数据

						let TabbarData = organizedData.flatMap(item => item.Node.filter(row => row.IsTabbar)).sort(
							(a, b) => a.APFunCode - b.APFunCode); // 对结果进行排序
						// console.log(TabbarData) 

						uni.removeStorageSync('ModuleInfo_All');
						uni.removeStorageSync('Module_Tabbar');

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'ModuleInfo_All',
							data: organizedData,
							StorageName: 'ModuleInfo_All',
							StorageData: JSON.stringify(organizedData),
						});

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'Module_Tabbar',
							data: TabbarData,
							StorageName: 'Module_Tabbar',
							StorageData: JSON.stringify(TabbarData),
						})


						let url = '';
						// 小工单/QMS直接跳转
						if (module.ModuleID == 2 || module.ModuleID == 3) {
							let homePage = module.authPages.find(item => item.IsHomepage);
							if (homePage && homePage != undefined) {
								url = homePage.AP_Link; // 设置首页路径
								uni.navigateTo({
									url: url
								})
							} else {
								uni.showToast({
									icon: 'none',
									title: '当前应用未设置首页!'
								})
							}
						} else {
							url = '/commonPage/Module/index?moduleID=' + module.ModuleID + '&index=0';
							uni.navigateTo({
								url: url
							})
						}
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'ActiveModule',
							data: module,
							StorageName: 'ActiveModule',
							StorageData: JSON.stringify(module),
						})
						that.$utils.hideLoading();
						// console.log(url);
					}
				}, (err) => {
					// 处理错误  
				});
			},

			// 进入上次APP模块
			initAPPModule() {
				let that = this;
				let str = uni.getStorageSync('ActiveModule');
				if (str) {
					let module = JSON.parse(str); // 上次选中APP模块

					this.initModule(module);
				}
			},

			// 切换版本
			changeCombo(e) {
				console.log(e);
				let that = this;
				// 重新获取菜单
				that.getAllMenuData(e, 2);
				// 获取当前版本看板列表
				that.getKanBanList();
			},

			// 基础选择页面
			openBaseScreen(str) {
				let obj = {};
				let url = '/commonPage/Tool/baseScreen?select=1';

				if (str == '看板') {
					obj = {
						allowClear: false,
						cmd: '',
						type: str,
						ListeningName: 'Home_Choice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'boardTitle', //查询结果显示的字段
							ChoiceDataKey: 'boardName',
							ChoiceDataData: this.selectedBoard.boardName
						},
						param: {
							data: this.boardList
						}
					}
				}

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	$h-padding: 5px;
	$v-padding: 10px;
	$radius: 5px;

	.comboSelect {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		font-weight: 500;
		width: 185px;
		border-radius: $radius;
	}

	.boardSelect {
		display: flex;
		align-items: center;
		margin-left: 15px;
		padding: 0 10px;
		height: 35px;
		font-size: 16px;
		font-weight: 500;
		background: rgba(0, 0, 0, .03);
		border-radius: $radius;

		.text {
			color: #fff;
			font-size: 14px;
			margin-right: 5px
		}
	}

	// 版本选择下拉
	.comboSelect /deep/ .uni-select__input-text {
		font-size: 14px;
		color: #fff;
	}

	.comboSelect /deep/ .uni-select {
		border: none;
	}

	.tabContent {
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		padding: $v-padding $h-padding;
		// padding-left: $h-padding;
		// padding-right: $h-padding;

		.head {
			position: fixed;
			left: 0;
			top: 0;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: calc(50px + #{$v-padding}) $h-padding $v-padding $h-padding;
			z-index: 2;
			width: 100vw;
			height: 150px;
			background-color: $main-background-color;

			&-top {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				&-left {
					display: flex;
					align-items: center;
					width: 350rpx;
					color: #fff;

					&-text {
						font-size: 32rpx;
						margin-right: 10rpx;
					}
				}
			}

			&-bottom {
				width: 100%;
				margin-top: $v-padding;
			}
		}


		.subcontent {
			display: flex;
			flex-direction: column;
			// padding: calc(50px + env(safe-area-inset-top) + #{$v-padding}) $h-padding $v-padding $h-padding;

			.commonBox {
				display: flex;
				flex-direction: column;
				padding: $v-padding $h-padding;
				background-color: #ffffff;
				margin-bottom: $v-padding;
				border-radius: 15rpx;

				&-title {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 0 $h-padding $v-padding $h-padding;

					&-left {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						width: 150rpx;
					}

					&-right {
						display: flex;
						justify-content: flex-end;
						align-items: center;
						width: 100rpx;
					}
				}

				&-content {
					display: flex;
					flex-direction: column;
				}
			}
		}
	}

	.grid-text {
		font-size: 14px;
		color: #909399;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}

	.shortcut {
		display: flex;
		flex-direction: column;
		height: 80vh;

		&-content {
			display: flex;
			flex: 1;
			padding: $v-padding $h-padding;
			background-color: #f7f7f7;

			.left_wrap {
				display: flex;
				flex-direction: column;
				width: 180rpx;

				.leftItem {
					display: flex;
					justify-content: center;
					align-items: center;
					height: 60rpx;
				}

				.leftItem.on {
					background-color: $main-background-color;
					color: #ffffff;
				}
			}

			.right_wrap {
				display: flex;
				flex-direction: column;
				flex: 1;

				.rightItem {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					font-size: 28rpx;
					margin-left: $h-padding;
				}

				.rightItem.on {
					background-color: $main-background-color;
					color: #ffffff;
				}
			}
		}

		&-bottom {
			display: flex;
			justify-content: center;
			align-items: center;
			position: fixed;
			width: 100%;
			height: 100rpx;
			padding: $v-padding $h-padding;
			left: 0;
			bottom: calc(100rpx + env(safe-area-inset-bottom) / 2);
		}
	}
</style>